import route from "@/router/index";
import { decrypt } from "@/utils/crypto";
import { message } from "ant-design-vue";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import axios from "axios";
import Cookies from 'js-cookie';

type responseType<T = any> = {
    message: string
    // 返回的数据
    result: T
}
const exclude:Array<string> = []
const excludeCode:Array<number>=[200,208]
class Request {
    Instance:AxiosInstance
  //  interceptors:AxiosInterceptorOptions
    constructor(config:AxiosRequestConfig){
        this.Instance = axios.create(config)
        this.Instance.interceptors.request.use((config:any)=>{
            if (Cookies.get("info")) {   //登录后添加验证签名
                config.headers['Authorization'] = 'Bear '+JSON.parse(decrypt(Cookies.get("info"))).authorization
            }
            return config
        })
        this.Instance.interceptors.response.use((response:AxiosResponse<any,responseType>)=>{
            if(!excludeCode.includes(response.data.code)){
                message.error(response.data.message)
            }
            if(response.data.code==401){
                Cookies.remove('info')
                route.push({name:'login'})
            }
            return response
        },(err: any)=>{
            return Promise.reject(err)
        })
    }

    request<T>(config:AxiosRequestConfig):Promise<T>{
        return new Promise((resolve,reject)=>{
            this.Instance.request({...config}).then((response:AxiosResponse<T>)=>{
                resolve(response.data)
            }).catch(err=>{
                reject(err)
            }).finally(()=>{
                
            })
        })
    }

    get<T>(config:AxiosRequestConfig):Promise<T>{
        return this.request({...config,method:'get'})
    }
    post<T>(config:AxiosRequestConfig):Promise<T>{
        return this.request({...config,method:'post'})
    }
    delete<T>(config:AxiosRequestConfig):Promise<T>{
        return this.request({...config,method:'delete'})
    }   
    put<T>(config:AxiosRequestConfig):Promise<T>{
        return this.request({...config,method:'put'})
    }
    update<T>(config:AxiosRequestConfig):Promise<T>{
        return this.request({...config,method:'update'})
    }
}

export default Request